import { ElMessage } from "element-plus";
import { ref, computed } from "vue";
import { defineStore } from "pinia";

export const useAnchorsStore = defineStore(
  "anchors",
  () => {
    // 锚点的节点
    const titles = ref([]);
    // markdown对象
    const preview = ref(null);
    // 生成锚点, 获取titles
    const anchor = () => {
      const anchors = preview.value.$el.querySelectorAll("h1,h2,h3,h4,h5,h6");
      const el = preview.value.$el;
      titles.value = Array.from(anchors).filter(
        (title) => !!title.innerText.trim()
      );
      if (!titles.value.length) {
        titles.value = [];
        return;
      }
      const hTags = Array.from(
        new Set(titles.value.map((title) => title.valuetagName))
      ).sort();
      titles.value = titles.value.map((el) => ({
        title: el.innerText,
        lineIndex: el.getAttribute("data-v-md-line"),
        indent: hTags.indexOf(el.tagName),
      }));
    };
    // 添加markdown对象
    const setPreview = (markdownObj) => {
      preview.value = markdownObj;
      // 生成锚点
      anchor()
    };
    // 点击目录时定位内容
    const handleAnchorClick = (anchor) => {
      const { lineIndex } = anchor;
      const heading = preview.value.$el.querySelector(
        `[data-v-md-line="${lineIndex}"]`
      );
      if (heading) {
        // 注意：如果你使用的是编辑组件的预览模式,则这里的方法名改为 previewScrollToTarget
        preview.value.previewScrollToTarget({
          target: heading,
          scrollContainer: window,
          top: 60,
        });
      }
    };

    return {
      titles,
      handleAnchorClick,
      setPreview,
    };
  },
  {
    persist: {
      key: "anchors",
      storage: sessionStorage,
      // paths: ["token", "loginUserInfo"],
      serializer: {
        deserialize: JSON.parse,
        serialize: JSON.stringify,
      },
    },
  }
);
